package util.server;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;

public class Server
{
	public static final String aidir = "ais";
	/**
	 * the port the server listens on for connections
	 */
	public static final int serverPort = 4567;
	
	/**
	 * creates a new server
	 * @param accdir the directory containing the accounts file (accounts.txt)
	 */
	public Server(String homedir)
	{
		ServerSocket ss = null;
		try
		{
			System.out.println("starting server...");
			ss = new ServerSocket(serverPort);
			
			while(!ss.isClosed())
			{
				Socket socket = ss.accept();
				new DownloadThread(socket, homedir).start();
			}
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
		finally
		{
			if(ss != null)
			{
				try
				{
					ss.close();
				}
				catch(IOException e)
				{
					e.printStackTrace();
				}
			}
		}
	}
	public static void main(String[] args)
	{
		new Server(args[0]);
	}
}
class DownloadThread extends Thread
{
	public DownloadThread(Socket s, String homedir) throws IOException
	{
		try
		{
			System.out.println("socket opened");
			DataInputStream dis = new DataInputStream(s.getInputStream());
			int length = dis.readInt();
			byte[] namedata = new byte[length];
			dis.read(namedata);
			Charset c = Charset.forName("UTF-8");
			String dlname = ""+c.decode(ByteBuffer.wrap(namedata));
			System.out.println("download name = "+dlname);
			
			length = dis.readInt();
			byte[] data = new byte[length];
			dis.read(data);
			System.out.println("file downloaded! "+length+" bytes");
			File aidir = new File(homedir+System.getProperty("file.separator")+Server.aidir);
			if(!aidir.exists() && !aidir.mkdir())
			{
				System.out.println("no ai directory detected and failed to create, exiting");
				System.exit(0);
			}
			File dl = new File(homedir+System.getProperty("file.separator")+Server.aidir+System.getProperty("file.separator")+dlname);
			FileOutputStream fos = new FileOutputStream(dl);
			System.out.print("writing to file... ");
			fos.write(data);
			System.out.println("done!");
		}
		finally
		{
			s.close();
			System.out.println("socket closed");
		}
	}
}